<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>取消请求</title>
</head>
<body>
    <button>发送</button>
    <button>取消</button>

    <script>
       // 声明 CancelToken 函数
       function CancelToken(executor){
            // 声明一个变量
            let resolvePromise;
            // 声明一个属性
            this.promise = new Promise((resolve=>{
                resolvePromise = resolve;
            }))
            executor(function(){
                resolvePromise();
            })
       }

       // 发送请求 axios   config = {method:'get',url:'http://127.0.0.1/timeout',cancelToken: new CancelToken(c=>{})}

       function axios(config){
            return new Promise((resolve,reject)=>{
                let xhr = new XMLHttpRequest();
                xhr.open(config.method, config.url);
                xhr.send();
                xhr.onreadystatechange = function(){
                    if(xhr.readyState === 4) {
                        if(xhr.status >=200 && xhr.status < 300){
                            resolve({
                                status:xhr.status,
                                statusText:xhr.statusText,
                                headers:xhr.getAllResponseHeaders(),
                                data: xhr.response,
                                request: xhr
                            })
                        }else{
                            reject(xhr.status);
                        }
                    }
                }
                 // 取消请求
                if(config.cancelToken){
                    // 有可能成功，也有可能是pending
                    config.cancelToken.promise.then(()=>{
                        xhr.abort();
                    })
                }
            })
           
       }

       let btns = document.querySelectorAll('button');
       let cancel = null;
       btns[0].onclick = function(){
            axios({
                url:'http://127.0.0.1:8080/timeout',
                method:'get',
                cancelToken:new CancelToken((c)=>{
                    cancel = c;
                })
            })
        }

       btns[1].onclick = function(){
            cancel();
       }

    </script>
</body>
</html>